package com.word.app.config;
import java.util.*;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.word.app.config.token.JWTToken;
import com.word.app.config.token.JWTUtil;
import com.word.app.pojo.UserInfo;


public class UserRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        // Map模拟数据库
        // Map<String, String> permissionMap = new HashMap<String,String>();
        // permissionMap.put("root", "user:add");
        // permissionMap.put("visitor", "user:visit");

        // if(permissionMap.keySet().contains(userName)){
        //     info.addStringPermission(permissionMap.get(userName));
        //     return info;
        // }
        
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        String userName = ((UserInfo)SecurityUtils.getSubject().getPrincipal()).getName();
        System.out.println(userName);
        if(userName.equals("root")){
            info.addStringPermission("perm:root");
            return info;
        }else{
            info.addStringPermission("perm:visitor");
            return info;
        }

        // // 无认证通过
        // SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // // UsernamePasswordToken usertoken = (UsernamePasswordToken) token;

        // Map<String, String> userInfoMap = new HashMap<String,String>();
        // userInfoMap.put("root", "root");
        // userInfoMap.put("visitor", "123");

        // if(!userInfoMap.keySet().contains(userName))
        //     return null;
        
        // // if(!usertoken.getUsername().equals(userInfo.getUsername()))
        // //     return null;

        String userName = JWTUtil.getUsername((String)token.getCredentials());
        UserInfo userinfo = new UserInfo();
        userinfo.setName(userName);
        System.out.println(userinfo);
        return new SimpleAuthenticationInfo(userinfo, (String)token.getCredentials(), "");

        // // 空认证通过
        // return new SimpleAuthenticationInfo(new UserInfo(), (String)token.getCredentials(), "");
    }
    
}
